package com.xtaller.sdboot.core.generator;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.sdboot.utils.helper.StrHelper;
import lombok.var;

import java.sql.*;

/**   
 * @author: Taller   
 * @date:   Mar 12, 2019 2:44:14 PM   
 * @version V1.0 
 * @Description: 数据库操作
 */
public class Conn {
	private String url, user, password, db, table;

	public Conn(JSONObject obj) {
		this.url = obj.getString("url");
		this.user = obj.getString("user");
		this.password = obj.getString("password");
		this.db = obj.getString("db");
		this.table = obj.getString("table");
	}

	/**
	 * 读取表注释
	 * */
	public ResultSet tableInfo() {
		var sql = StrHelper.join("SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_NAME='",
				table ,"' AND table_schema='",
				db ,"'");
		return run(sql);
	}
	/**
	 * 读取表结构
	 * */
	public ResultSet tableColumn() {
		var sql = StrHelper.join("SELECT COLUMN_Name,data_type,COLUMN_COMMENT from information_schema.columns WHERE TABLE_NAME='",
				table ,"' AND table_schema='",
				db ,"'");
		return run(sql);
	}

	/**
	 * 获取连接
	 * */
	private Connection get() {
		try {
			return DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 数据库查询
	 * */
	private ResultSet run(String sql) {
		var conn = get();
		ResultSet rs;
		try {
			PreparedStatement pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rs = null;
		}
        return rs;
	}
}
